<template>
  <div class="notes-container">
    <PageHeader title="笔记资源" />
    <div class="notes-content">
      <!-- 移动端菜单按钮 -->
      <button class="mobile-menu-btn" @click="showMobileMenu = !showMobileMenu" v-if="isMobile">
        {{ showMobileMenu ? '关闭菜单' : '打开菜单' }}
      </button>

      <!-- 左侧文件夹导航 -->
      <div class="folder-nav" :class="{ 'mobile-visible': showMobileMenu }">
        <div class="search-box">
          <input type="text" placeholder="搜索笔记..." v-model="searchQuery">
        </div>
        <div class="folder-list">
          <FolderItem
            v-for="item in folderData"
            :key="item.path"
            :file="item"
            :expanded-folders="expandedFolders"
            :current-path="currentPath"
            @toggle="toggleFolder"
            @select="handleItemClick"
          />
        </div>
      </div>

      <!-- 右侧内容展示 -->
      <div class="content-view">
        <div v-if="!selectedFile" class="empty-state">
          <p>请从左侧选择一个笔记文件</p>
        </div>
        <div v-else class="file-content">
          <div class="file-header">
            <h3>{{ selectedFile.name }}</h3>
            <button @click="toggleEditMode" class="edit-toggle-btn">
              {{ isEditMode ? '预览' : '编辑' }}
            </button>
          </div>
          <div class="file-meta">
            <span>路径: {{ selectedFile.path }}</span>
          </div>
          <div class="file-body">
            <!-- 使用Vditor展示Markdown内容 -->
            <div ref="vditorRef" class="vditor-preview"></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch } from 'vue';
import PageHeader from '@/components/PageHeader.vue';
import type { FolderFileInfo } from '@/dataType/fileType';
import { notesService } from '@/services/notesService';
import Vditor from 'vditor';
import 'vditor/dist/index.css';
import FolderItem from '@/components/FolderItem.vue';

// 响应式状态
const expandedFolders = ref<string[]>([]);
const selectedFile = ref<FolderFileInfo | null>(null);
const currentPath = ref<string>('');
const searchQuery = ref<string>('');
const isMobile = ref<boolean>(false);
const showMobileMenu = ref<boolean>(false);
const fileContent = ref<string>('');
const vditorRef = ref<HTMLElement | null>(null);
const vditorInstance = ref<Vditor | null>(null);
const isEditMode = ref<boolean>(false);

// 模拟文件夹数据
const folderData = ref<FolderFileInfo[]>([]);

// 方法
const toggleFolder = (path: string) => {
  if (expandedFolders.value.includes(path)) {
    expandedFolders.value = expandedFolders.value.filter(p => p !== path);
  } else {
    expandedFolders.value.push(path);
  }
};

const handleItemClick = (item: FolderFileInfo) => {
  currentPath.value = item.path;
  if (item.file) {
    selectedFile.value = item;
    notesService.getMarkdownContent(item.path).then(data => {
      fileContent.value = data;
      initVditor();
    })
    // 在移动端选择文件后自动隐藏菜单
    if (isMobile.value) {
      showMobileMenu.value = false;
    }
  } else {
    toggleFolder(item.path);
  }
};

// 监听窗口大小变化
const handleResize = () => {
  isMobile.value = window.innerWidth < 768;
  // 在桌面模式下确保菜单可见
  if (!isMobile.value) {
    showMobileMenu.value = true;
  }
};
//构建vditor组件
const initVditor = () => {
  if (!vditorRef.value) {
    return;
  }
  if (vditorInstance.value) {
    vditorInstance.value.destroy();
  }
  vditorInstance.value = new Vditor(vditorRef.value, {
    value: fileContent.value,
    placeholder: "请输入内容",
    counter: {
      enable: true,
      type: "markdown",
    },
    toolbarConfig:{
      hide:!isEditMode.value,
    },
    cache: {
      enable: false,
    },
    blur: (value: string) => {
      fileContent.value = value;
      if(selectedFile.value){
        //失去焦点进行文件保存
        notesService.saveMarkdownContent(selectedFile.value?.path,value);
      }
    },
    outline: {
      enable: true,
      position: "right",
    },
    height: "100%",
    width: "100%",
    after:async()=>{
      //不是编辑状态进行预览
      if(isEditMode.value){
        return;
      }
      // 拿到工具栏下面的所有button
      const buttons: NodeListOf<Element> = document.querySelectorAll(".vditor-toolbar button");
      // 遍历每个按钮并查找具有 data-type="preview" 的按钮
      buttons.forEach((button: any) => {
        if (button.getAttribute("data-type") === "preview") {
          // 如果按钮的 data-type 属性是 preview，则模拟点击该按钮
          button.click();
        }
      });
    }
  });
}
const toggleEditMode = () => {
  isEditMode.value = !isEditMode.value;
  initVditor();
};

onMounted(() => {
  handleResize();
  window.addEventListener('resize', handleResize);
  // 从服务端获取文件目录列表
  notesService.listFiles('').then(data => {
    folderData.value = data;
  });
  // 默认展开第一个文件夹
  if (folderData.value.length > 0) {
    toggleFolder(folderData.value[0].path);
  }
});
onUnmounted(() => {
  if (vditorInstance.value) {
    vditorInstance.value.destroy();
  }
});

</script>
<style scoped>
.notes-container {
  width: calc(100vw - 62px);
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 20px;
}

.notes-content {
  display: flex;
  flex: 1;
  height: calc(100vh - 60px);
  overflow: hidden;
}

.folder-nav {
  width: 280px;
  background-color: #f5f5f5;
  border-right: 1px solid #e0e0e0;
  display: flex;
  flex-direction: column;
  height: calc(100vh - 100px); /* 固定高度，减去顶部和底部间距 */
  overflow: hidden;
  transition: transform 0.3s ease;
}

.search-box {
  padding: 12px;
  border-bottom: 1px solid #e0e0e0;
}

.search-box input {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 0.9rem;
}

.folder-list {
  flex: 1;
  overflow-y: auto;
  padding: 10px 0;
  height: calc(100% - 56px); /* 使用height而非max-height确保占满剩余空间 */
}

.folder-item {
  margin-bottom: 4px;
}

.folder-header {
  display: flex;
  align-items: center;
  padding: 8px 16px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.folder-header:hover {
  background-color: rgba(0, 0, 0, 0.05);
}

.folder-header.active {
  background-color: rgba(30, 136, 229, 0.1);
  color: #1E88E5;
  font-weight: 500;
}

.icon {
  margin-right: 8px;
  font-size: 1.2rem;
}

.name {
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.subfolders {
  padding-left: 24px;
  border-left: 1px dashed #ddd;
  margin-left: 8px;
}

.subfolder-item {
  margin-top: 4px;
}

.content-view {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background-color: #fff;
}

.empty-state {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 1.1rem;
}

.file-content {
  margin: 0 auto;
}

.file-meta {
  color: #666;
  font-size: 0.9rem;
  margin: 10px 0 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.file-body {
  line-height: 1.6;
  color: #333;
  min-height: 300px;
}

.vditor-preview {
  min-height: 300px;
  padding: 15px;
  border: 1px solid #eee;
  border-radius: 4px;
}

.mobile-menu-btn {
  display: none;
  position: fixed;
  bottom: 20px;
  right: 20px;
  z-index: 100;
  padding: 10px 16px;
  background-color: #1E88E5;
  color: white;
  border: none;
  border-radius: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  cursor: pointer;
}

@media (max-width: 768px) {
  .folder-nav {
    position: fixed;
    left: 0;
    top: 60px;
    bottom: 0;
    z-index: 10;
    transform: translateX(-100%);
  }

  .folder-nav.mobile-visible {
    transform: translateX(0);
  }

  .content-view {
    padding: 15px;
  }

  .mobile-menu-btn {
    display: block;
  }
}
.file-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}
.edit-toggle-btn {
  padding: 6px 12px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}
.edit-toggle-btn:hover {
  background-color: #359469;
}
</style>
